//
//  JobDetailViewController.swift
//  GreenDeal
//
//  Created by Moennig Q on 26/12/2022.
//

import UIKit
import RxCocoa
import RxSwift
import RxGesture
import CoreLocation
import MJRefresh
import YJLocationConverter
class JobDetailViewController: BaseViewController {
    fileprivate lazy var disposeBag = DisposeBag()
    var reloadPVDsListClosure: (()->Void)?//关闭detail后，要刷新installation list中对应的cell，处理cell中某些数据的改变（状态，数量，姓名等）
    var skipToWhere: SkipToWhere?
    let customView = JobDetailView()
    //
    var devationLocation: LocationModel = LocationModel()
    var panelInstalledLcation: LocationModel = LocationModel() //点击panel installed时定位到的当前位置信息
    var panelInstalledLatitudeKey: String = ""
    var panelInstalledLongitudeKey: String = ""
    var panelInstalledDateOfCompletionKey: String = ""
    var panelInstalledDateOfCompletion: String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initView()
        self.loadData(true,checkIfNeedResignFlag: true)
        Tool().requestCurrentLocation()
    }
    func initView(){
        self.view = self.customView
        //
        self.customView.scrollView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(headerLoad(_:)))
        self.customView.loadFaildView.retryBtn.rx.tap.subscribe{ [weak self]  _ in
            guard let strongSelf = self else {return}
            strongSelf.loadData(true ,checkIfNeedResignFlag: true)
        }.disposed(by: self.disposeBag)
        //back to pre
        self.customView.backToPreBtn.rx.tap.subscribe { [weak self] _ in
            self?.backToPre()
        }.disposed(by: self.disposeBag)
        //Refresh
        self.customView.refreshBtn.rx.tap.subscribe { [weak self] _ in
            self?.loadData(true)
        }.disposed(by: self.disposeBag)
        //MARK: - edit owner info
        self.customView.topView.propertyTypeImageView.rx.tapGesture().when(.recognized).subscribe {[weak self] _ in
            guard let strongSelf = self else {return}
            if JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag {
                let editVC = EditOwnerInfomationViewController()
                editVC.hidesBottomBarWhenPushed = true
                strongSelf.navigationController?.pushViewController(editVC, animated: false)
            }
        }.disposed(by: self.disposeBag)
        //MARK: - installation type info
        self.customView.topView.installationTypeImageView.rx.tapGesture().when(.recognized).subscribe { [weak self] _ in
            guard let strongSelf = self else {return}
            if JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag {
                let editVC = EditInstallationTypeViewController()
                editVC.hidesBottomBarWhenPushed = true
                strongSelf.navigationController?.pushViewController(editVC, animated: false)
            }
        }.disposed(by: self.disposeBag)
        //MARK: - topview: 编辑地址
        self.customView.topView.editAddressBtn.rx.tapGesture().when(.recognized).subscribe {[weak self] _ in
            guard let strongSelf = self else {return}
            if JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag{
                let editVC = EditInstallAddressViewController()
                editVC.refreshDetailClosure = {
                    strongSelf.loadData(false)
                }
                editVC.hidesBottomBarWhenPushed = true
                strongSelf.navigationController?.pushViewController(editVC, animated: false)
            }
        }.disposed(by: self.disposeBag)
        //MARK: - topview: call owner phone
        self.customView.topView.phoneBtn.rx.tap.subscribe { _ in
            InstallationDetailVCHelper.shared.callPhone(JobDetailModelHelper.shared.jobDetailModel.owner_address.phone)
        }.disposed(by: self.disposeBag)
        //MARK: - topview: email
        self.customView.topView.emailBtn.rx.tap.subscribe { _ in
            InstallationDetailVCHelper.shared.sendEmail(JobDetailModelHelper.shared.jobDetailModel.owner_address.email)
        }.disposed(by: self.disposeBag)
        //MARK: - topview: map navigation by  address
        self.customView.topView.mapNaviBtn.rx.tap.subscribe { [weak self]_ in
            guard let strongSelf = self else {return }
            let addressModel = DeliveryWarehouseModel()
            if JobDetailModelHelper.shared.jobDetailModel.install_address.special_address != "" {
                addressModel.special_address = JobDetailModelHelper.shared.jobDetailModel.install_address.special_address
            }else{
                let latitude = JobDetailModelHelper.shared.jobDetailModel.install_address.location.latitude
                let longitude = JobDetailModelHelper.shared.jobDetailModel.install_address.location.longitude
                addressModel.latitude = latitude
                addressModel.longitude = longitude
                addressModel.street_number = JobDetailModelHelper.shared.jobDetailModel.install_address.street_number
                addressModel.street_name = JobDetailModelHelper.shared.jobDetailModel.install_address.street_name
                addressModel.street_type = JobDetailModelHelper.shared.jobDetailModel.install_address.street_type
                addressModel.suburb = JobDetailModelHelper.shared.jobDetailModel.install_address.suburb
                addressModel.state = JobDetailModelHelper.shared.jobDetailModel.install_address.state
                addressModel.post_code = JobDetailModelHelper.shared.jobDetailModel.install_address.post_code
            }
            MapNavigationHelper.shared.showMapsOptions(addressModel,vc: strongSelf)
        }.disposed(by: self.disposeBag)
        //MARK: - pick up address: map navigation by  address
        self.customView.pickupAddressView.mapNaviBtn.rx.tap.subscribe { [weak self]_ in
            guard let strongSelf = self else {return }
            let addressModel = DeliveryWarehouseModel()
            let deliverAddressModel = JobDetailModelHelper.shared.jobDetailModel.delivery_address
            let latitude = deliverAddressModel.latitude
            let longitude = deliverAddressModel.longitude
            addressModel.latitude = latitude
            addressModel.longitude = longitude
            addressModel.street_number = deliverAddressModel.street_number
            addressModel.street_name = deliverAddressModel.street_name
            addressModel.street_type = deliverAddressModel.street_type
            addressModel.suburb = deliverAddressModel.suburb
            addressModel.state = deliverAddressModel.state
            addressModel.post_code = deliverAddressModel.post_code
            MapNavigationHelper.shared.showMapsOptions(addressModel,vc: strongSelf)
        }.disposed(by: self.disposeBag)
        //MARK: - 复制installation地址
        self.customView.topView.addressLabelLongPressGestureClosure = {[weak self] in
            guard let strongSelf = self else {return }
            InstallationDetailVCHelper.shared.copyContentToPasteBoard(content: strongSelf.customView.topView.addressLabel.text ?? "",parentView: strongSelf.customView)
        }
        //MARK: - 复制installation地址
        self.customView.pickupAddressView.pickupAddressLabelLongPressGestureClosure = {[weak self] in
            guard let strongSelf = self else {return }
            InstallationDetailVCHelper.shared.copyContentToPasteBoard(content: strongSelf.customView.pickupAddressView.pickupAddressLabel.text ?? "",parentView: strongSelf.customView)
        }
        //MARK: - edit grid-connected
        self.customView.topView.gridConnectedImageView.rx.tapGesture().when(.recognized).subscribe { [weak self] _ in
            guard let strongSelf = self else {return}
            if JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag {
                let editVC = EditGridConnectedViewController()
                editVC.hidesBottomBarWhenPushed = true
                editVC.refreshDetailClosure = {
                    strongSelf.loadData(false)
                }
                strongSelf.navigationController?.pushViewController(editVC, animated: false)
            }
        }.disposed(by: self.disposeBag)
        //MARK: - 跳转到spv的tip界面
        self.customView.systemInfoView.spvView.rx.tapGesture().when(.recognized).subscribe { [weak self] _ in
            guard let strongSelf = self else {return}
            strongSelf.toSPVTipVC()
        }.disposed(by: self.disposeBag)
        //MARK: - edit system info View
        self.customView.systemInfoView.editSystemInfoBtn.rx.tapGesture().when(.recognized).subscribe { [weak self] _ in
            guard let strongSelf = self else {return}
            if JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag{
                let editVC = EditSystemInfoViewController()
                editVC.refreshDetailClosure = {
                    strongSelf.loadData(false)
                }
                editVC.hidesBottomBarWhenPushed = true
                strongSelf.navigationController?.pushViewController(editVC, animated: false)
            }
        }.disposed(by: self.disposeBag)
        //MARK: - edit panel info
        self.customView.systemInfoView.panelTableView.rx.itemSelected.bind { [weak self] (_) in
            guard let strongSelf = self else {return}
            if JobDetailModelHelper.shared.jobDetailModel.canEditPanelInfoFlag{//panel的编辑特别处理，因为设计到panel installed后也不能编辑了
                let editVC = EditPanelInfoViewController()
                editVC.refreshDetailClosure = {
                    strongSelf.loadData(false)
                }
                editVC.hidesBottomBarWhenPushed = true
                strongSelf.navigationController?.pushViewController(editVC, animated: false)
            }
        }.disposed(by: disposeBag)
        //MARK: - edit inverter info
        self.customView.systemInfoView.inverterTableView.rx.itemSelected.bind { [weak self] (_) in
            guard let strongSelf = self else {return}
            if JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag{
                let editVC = EditInverterInfoViewController()
                editVC.refreshDetailClosure = {
                    strongSelf.loadData(false)
                }
                editVC.hidesBottomBarWhenPushed = true
                strongSelf.navigationController?.pushViewController(editVC, animated: false)
            }
        }.disposed(by: disposeBag)
        //MARK: - edit battery info
        self.customView.systemInfoView.batteryTableView.rx.itemSelected.bind { [weak self] (_) in
            guard let strongSelf = self else {return}
            if JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag{
                let editVC = EditBatteryInfoViewController()
                editVC.hidesBottomBarWhenPushed = true
                strongSelf.navigationController?.pushViewController(editVC, animated: false)
            }
        }.disposed(by: disposeBag)
        //MARK: - to panel list
        self.customView.checklistTableView.toPanelListClickClosure = {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.toPanelNumersVC()
        }
        //MARK: - to inverter list
        self.customView.checklistTableView.toInverterListClickClosure = {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.toInverterNumberVC()
        }
        //MARK: - to der register list
        self.customView.checklistTableView.toDERRegisterClosure = {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.toDERRegister()
        }
        //MARK: - panel installed
        self.customView.checklistTableView.toPanelInstallClosure = {[weak self] in
            guard let strongSelf = self else {return}
            //没有panel installed
            if !JobDetailModelHelper.shared.jobDetailModel.spv_installed {
                strongSelf.getDetailBeforePanelInstalled()
            }
        }
        //MARK: - to images list
        self.customView.checklistTableView.toImageListClosure = { [weak self](currentIndex) in
            guard let strongSelf = self else {return}
            strongSelf.toImageListVC(currentIndex)
        }
        //MARK: - signatures
        self.customView.checklistTableView.toSignatureClosure = { [weak self](signType) in
            guard let strongSelf = self else {return}
            strongSelf.xp_readyToSign(signType)
        }
        //MARK: - to edit checklist text
        self.customView.checklistTableView.toEditTextClosure = { [weak self](checklistModel) in
            guard let strongSelf = self else {return}
            strongSelf.showEditCheckListText(checklistModel)
        }
        //MARK: - to edit checklist bool
        self.customView.checklistTableView.toClickChecklitBoolItemClosure = { [weak self](index) in
            guard let strongSelf = self else {return}
            if JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag{
                strongSelf.toClickBoolItemOfChecklist(index)
            }
        }
        
        //MARK: - support function - Flush upload
        self.customView.supportFunctionView.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            guard  JobDetailModelHelper.shared.jobDetailModel.canEditJobDetailFlag else {return}
            strongSelf.flushUpload(.flushUpload)
        }).disposed(by: self.disposeBag)
        //MARK: - support
        self.customView.supportView.tableView.rx.itemSelected.bind { [weak self](indexPath) in
            guard let strongSelf = self else {return}
            let type = strongSelf.customView.supportView.dataObserver.value[indexPath.row]
            if type == SupportType.phone {
                InstallationDetailVCHelper.shared.callPhone(APPConfig.SupportPhone)
            }else if type == SupportType.email {
                InstallationDetailVCHelper.shared.sendEmail(APPConfig.SupportEmail)
            }
        }.disposed(by: disposeBag)
        //MARK: - bottom 跳转到panel and inverter 位置
        self.customView.bottomView.barcodeBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else {return}
            strongSelf.skipToViewPosition(R.string.localizable.preinstallationE())
        }).disposed(by: self.disposeBag)
        //MARK: - bottom 跳转到panel and inverter 位置
        self.customView.bottomView.checklistBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else {return}
            strongSelf.skipToViewPosition(R.string.localizable.on_SITESELFIE())
        }).disposed(by: self.disposeBag)
        //MARK: - bottom 跳转到signature 位置
        self.customView.bottomView.signatureBtn.rx.controlEvent(.touchUpInside).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else {return}
            strongSelf.skipToViewPosition(R.string.localizable.signatureS())
        }).disposed(by: self.disposeBag)
        //MARK: - 设置navigation title info
        self.customView.setTitleInfo(JobDetailModelHelper.shared.jobDetailModel.owner_address.type_name, subTitle: JobDetailModelHelper.shared.jobDetailModel.gwt_id)
        //MARK: - finish job
        self.customView.finishJobBtn.rx.tap.subscribe { [weak self] _ in
            guard let strongSelf = self else {return}
            strongSelf.finishJob()
        }.disposed(by: self.disposeBag)
        //MARK: - reopen job
        self.customView.reopenJobBtn.rx.tap.subscribe { [weak self] _ in
            guard let strongSelf = self else {return}
            strongSelf.reopenJob()
        }.disposed(by: self.disposeBag)
        
        //MARK: 获取DateOfCompletion key值
        self.panelInstalledLatitudeKey = JobDetailModelHelper.shared.jobDetailModel.id + "Latitude"
        self.panelInstalledLongitudeKey = JobDetailModelHelper.shared.jobDetailModel.id + "Longitude"
        self.panelInstalledDateOfCompletionKey = JobDetailModelHelper.shared.jobDetailModel.id + "DateOfCompletion"
        //MARK: - 进入Job自动上传本地数据,上传完自动刷新数据
        UploadManager.shared.uploadLocalDataByPVDJob(JobDetailModelHelper.shared.jobDetailModel.id,uploadingClosure: {[weak self]( needUploadCnt, uploadSuccessCnt, uploadFaildCnt) in
            guard let strongSelf = self else {return}
            if  needUploadCnt == (uploadSuccessCnt + uploadFaildCnt){
                strongSelf.loadData(false)
            }
        })
    }
    //MARK: - 跳转到spv提示界面
    func toSPVTipVC(){
        let view = JobDetailSPVTipView()
        view.learnMoreClosure = {
            let vc = AttachmentViewController()
            vc.attchmentType = .OtherLink
            vc.attachmentURL = APPConfig.SPVLearnMoreLink
            self.navigationController?.pushViewController(vc, animated: false)
        }
        ModelViewUtil.shared.showAlertView(view)
    }
    override func backToPre() {
        self.reloadPVDsListClosure?()//刷新list中status，数量，地址等的变化，detail中可能
        self.navigationController?.popViewController(animated: true)
    }
    //notloadingFlag is false by default for first loading and refresh data
    func loadData(_ loadingFlag: Bool, header: MJRefreshNormalHeader? = nil,cacheFlag: Bool = true,checkIfNeedResignFlag: Bool = false)
    {
        //set block
        let viewModel = JobDetailService()
        viewModel.setBlockAfterNetwork({ [weak self](result , otherInfo) -> Void in
            guard let strongSelf = self else {return}
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            if let _ = header{
                header?.endRefreshing()
            }
            if strongSelf.customView.scrollView.isHidden {//防止缓存数据加载一次，网络数据又加载一次，导致skipToWhere后跳转不准确
                strongSelf.customView.showDetailView()
            }
            //是否跳转到的panel tab 页面，跳转完成后置空
            if let toWhere = strongSelf.skipToWhere {
                switch toWhere {
                case .Panel,.Inverter:
                    strongSelf.skipToViewPosition(R.string.localizable.preinstallationE())
                    if toWhere == .Panel {
                        strongSelf.toPanelNumersVC(false)
                    }else if toWhere == .Inverter{
                        strongSelf.toInverterNumberVC(false)
                    }
                case .Checklist:
                    strongSelf.skipToViewPosition(R.string.localizable.on_SITESELFIE())
                case .Signature:
                    strongSelf.skipToViewPosition(R.string.localizable.signatureS())
                default:
                    break
                }
                strongSelf.skipToWhere = nil
            }
            //检查是否需要重签
            let resignMsg = JobDetailModelHelper.shared.jobDetailModel.re_sign_statement_message
            if checkIfNeedResignFlag && resignMsg != "" && Connectivity.isConnectedToInternet {//true表示需要检查是否有重新签名的提示信息
                Tool().showAlertViewWithOneBtn(message: resignMsg) {
                    strongSelf.readResignStatementMsg()
                }
            }
        }) { (code, error) -> Void in
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            if code == APICustomStatusCode.RequestFaild.rawValue{//网络请求错误才显示Retry
                self.customView.showFaildView()
            }
            Tool().showErrorInfo(code, error)
        }
        if loadingFlag {
            //add Loading view
            ModelViewUtil.shared.showLoadingView()
        }
        viewModel.getInstallationsDetail(cacheFlag: true)
    }
    //标记已读
    private func readResignStatementMsg(){
        let vm = JobDetailService()
        vm.setBlockAfterNetwork { result, _ in
            if let data = result as? PVDDetailModel{
                JobDetailModelHelper.shared.jobDetailModel.re_sign_statement_message = data.re_sign_statement_message
            }
        } errorBlock: { _,_ in
            
        }
        vm.readResignStatementMsg()
    }
    @objc func headerLoad(_ hearder: MJRefreshNormalHeader){
        self.loadData(false,header: hearder, checkIfNeedResignFlag: true)
    }
    
    //MARK: 2024-03-03 - 前往签名
    private func xp_readyToSign(_ signType: SignatureType){
        let infoModel = APPConfig.loginInfo
        let model = JobDetailModelHelper.shared.jobDetailModel
        
        if model.job_status == "2" { // SWH(热水器)
            if model.signatures.installer_accredited_number == infoModel.plumber_licenses {
                let vc = ResignViewController()
                vc.signatureType = signType
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }else{
            
            let list = model.system_detail.installation_date.components(separatedBy: "/")
            var installation_dateString : String = ""
            if list.count == 3 {
                installation_dateString = (list.last ?? "") + "-"
                installation_dateString = installation_dateString + list[1] + "-"
                installation_dateString = installation_dateString + (list.first ?? "")
            }
                        
            
            let dateFormatter = DateFormatter()
            dateFormatter.locale = Locale(identifier: "en-au")
            dateFormatter.dateFormat =  "yyyy/MM/dd"
            
            let installation_date : Date = dateFormatter.date(from:installation_dateString) ?? Date()
            let effective_date : Date = dateFormatter.date(from: infoModel.effective_date) ?? Date()
            
            let installer_accredited_number : String = model.signatures.installer_accredited_number
            
            let designerAccreditation = model.signatures.designer_accredited_number
            if installer_accredited_number.count > 0 { //installer可以重签所有的签名
                if installation_date >= effective_date { /// saa 生效
                    if installer_accredited_number == infoModel.saaNumber {
                        if InstallationSignatureService().setDataInfo(self).checkIfNeedResign(signType) {
                            let vc = ResignViewController()
                            vc.signatureType = signType
                            self.navigationController?.pushViewController(vc, animated: true)
                        }else{
                            InstallationSignatureService().setDataInfo(self).toSignature(signType)
                        }
                    }
                }else{
                    if installer_accredited_number == infoModel.accreditedNumber {
                        if InstallationSignatureService().setDataInfo(self).checkIfNeedResign(signType) {
                            let vc = ResignViewController()
                            vc.signatureType = signType
                            self.navigationController?.pushViewController(vc, animated: true)
                        }else{
                            InstallationSignatureService().setDataInfo(self).toSignature(signType)
                        }
                    }
                }
            }else if designerAccreditation.count > 0 {//designer只能重签designer角色的签名
                if installation_date >= effective_date { /// saa 生效
                    if designerAccreditation == infoModel.saaNumber {
                        if signType == .Designer {
                            if InstallationSignatureService().setDataInfo(self).checkIfNeedResign(signType) {
                                let vc = ResignViewController()
                                vc.signatureType = signType
                                self.navigationController?.pushViewController(vc, animated: true)
                            }else{
                                InstallationSignatureService().setDataInfo(self).toSignature(signType)
                            }
                        }
                    }
                }else{
                    if designerAccreditation == infoModel.accreditedNumber {
                        if signType == .Designer {
                            if InstallationSignatureService().setDataInfo(self).checkIfNeedResign(signType) {
                                let vc = ResignViewController()
                                vc.signatureType = signType
                                self.navigationController?.pushViewController(vc, animated: true)
                            }else{
                                InstallationSignatureService().setDataInfo(self).toSignature(signType)
                            }
                        }
                    }
                }
            }
            
        }
        
//        /// STC :
//        if model.signatures.installer_accredited_number == APPConfig.loginInfo.accreditedNumber {
//            
//        }else if model.signatures.installer_accredited_number == APPConfig.loginInfo.saaNumber {
//            
//        }
        
        ///SWH
//        if model.signatures.installer_accredited_number == model.
    }
    
    
    
    //MARK: - 准备去签名
    private func readyToSign(_ signType: SignatureType){
        if JobDetailModelHelper.shared.jobDetailModel.isInstallerFlag{//installer可以重签所有的签名
            if InstallationSignatureService().setDataInfo(self).checkIfNeedResign(signType) {
                let vc = ResignViewController()
                vc.signatureType = signType
                self.navigationController?.pushViewController(vc, animated: true)
            }else{
                InstallationSignatureService().setDataInfo(self).toSignature(signType)
            }
        }else if JobDetailModelHelper.shared.jobDetailModel.isDesignerFlag{//designer只能重签designer角色的签名
            if signType == .Designer {
                if InstallationSignatureService().setDataInfo(self).checkIfNeedResign(signType) {
                    let vc = ResignViewController()
                    vc.signatureType = signType
                    self.navigationController?.pushViewController(vc, animated: true)
                }else{
                    InstallationSignatureService().setDataInfo(self).toSignature(signType)
                }
            }
        }
    }
    private func toPanelNumersVC(_ animate: Bool = true) {
        let vc = JobDetailPanelsListViewController()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: animate)
        
    }
    //MARK: - 跳转到某个位置部分， scan，signature，checklist
    fileprivate func skipToViewPosition(_ title: String){
        //跳转到scan部分
        if let row = JobDetailModelHelper.shared.jobDetailModel.pvd_checklists.firstIndex(where: {$0.title == title && ($0.type == ChecklistType.headerWithImage.rawValue || $0.type == ChecklistType.header.rawValue)}){
            let recOnTableView = self.customView.checklistTableView.rectForRow(at: IndexPath(row: row, section: 0))
            let cellPointOnScrollView = self.customView.checklistTableView.convert(recOnTableView.origin, to: self.customView.scrollView)
            self.customView.scrollView.scrollToView(point: cellPointOnScrollView, animated: true)
        }
    }
    //MARK: - reopen job
    private func reopenJob(){
        if JobDetailModelHelper.shared.jobDetailModel.isInstallerFlag {//installer才能reopen job
            let vm = JobDetailService()
            vm.setBlockAfterNetwork({ (result , _) -> Void in
                ModelViewUtil.shared.hideLoadingView()
                JobDetailModelHelper.shared.jobDetailModel.job_status = PVDJobStatusValue.installing.rawValue
                Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.reopenedJob", comment: "")) {
                    InstallationDetailVCHelper.shared.cacheData()
                }
            }) {(code, error) -> Void in
                ModelViewUtil.shared.hideLoadingView()
                Tool().showErrorInfo(code, error)
                
            }
            //add Loading view
            ModelViewUtil.shared.showLoadingView(NSLocalizedString("pvd.detail.reopenJob", comment: ""))
            vm.reopenJob()
        }
    }
    //MARK: - finish job
    private func finishJob(){
        if !Connectivity.isConnectedToInternet {
            Tool().showFailureInfo()
            return
        }
        if JobDetailModelHelper.shared.jobDetailModel.isInstallerFlag {//installer才能finish job
            //local data need to upload before finish job
            if JobDetailModelHelper.shared.jobDetailModel.detailModifyFlag {
                self.alertViewWithUpload(message: NSLocalizedString("pvd.detail.localdata.check.uploaded", comment: ""),toContinueType: .finishJob)//"1": to finish job
            }else{
                InstallationDetailVCHelper.shared.cacheJobDetail(NSLocalizedString("pvd.detail.finishJob", comment: "")) {
                    self.requestFinishJobAPI(APPConfig.currentLocation.combineStr)
                } faildClosure: { code, error in
                    Tool().showErrorInfo(code,error)
                }
            }
        }
    }
    
    //MARK: 请求finish job api
    private func requestFinishJobAPI(_ loactionStr: String = ""){
        if Connectivity.isConnectedToInternet {
            //校验checklit，signatures，panel numbers所有的必填项
            if InstallationDetailVCHelper.shared.checkRequiredWhenFinishJob() {
                let vm = JobDetailService()
                vm.setBlockAfterNetwork({ [weak self](result , _) -> Void in
                    ModelViewUtil.shared.hideLoadingView()
                    guard let strongSelf = self else { return  }
                    //必须缓存Job status的数据，防止无网络刷新数据又显示finish job的问题
                    JobDetailModelHelper.shared.jobDetailModel.job_status = PVDJobStatusValue.installed.rawValue
                    InstallationDetailVCHelper.shared.cacheData()

                    if JobDetailModelHelper.shared.jobDetailModel.der_register {
                        strongSelf.alertViewWithDER()
                    }else{
                        Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.finishedJob", comment: ""))
                        {
                            if let data = JobDetailModelHelper.shared.jobDetailModel.installer_rating_id{
                                strongSelf.toAPPCommnt(data)
                            }
                        }
                    }

                }) { (code, error) -> Void in
                    ModelViewUtil.shared.hideLoadingView()
                    Tool().showErrorInfo(code,error)
                }
                //add Loading view
                ModelViewUtil.shared.showLoadingView(NSLocalizedString("pvd.detail.finishJob", comment: ""))
                vm.finishJob(loactionStr)
            }
            
            
        }else{
            Tool().showFailureInfo()
        }
        
    }
    //MARK: - finish job时，提示是否去Der Register
    private func alertViewWithDER(){
        let view = FinishJobAlertViewForDerRegister()
        view.toDERRegistClose = {
            self.toDERRegister()
        }
        //需要弹出App评分功能
        if let data = JobDetailModelHelper.shared.jobDetailModel.installer_rating_id{
            view.okClosure = {[weak self] in
                guard let strongSelf = self else {return}
                strongSelf.toAPPCommnt(data)
            }
        }
        ModelViewUtil.shared.showAlertView(view)
    }
    //MARK: - rate id 用户提交对应的APP评分
    private func toAPPCommnt(_ rateId: Int){
        
        let view = AppCommentView()
        view.submitClosure = {  (model) in
            model.id = rateId
            let vm = JobDetailService()
            vm.setBlockAfterNetwork { (result, _) in
                if model.ignoreFlag == false{//submit时才显示submitting
                    ModelViewUtil.shared.hideLoadingView()
                }
                view.removeFromSuperview()
            } errorBlock: { code, errMsg in
                if model.ignoreFlag == false{//submit时才显示submitting
                    ModelViewUtil.shared.hideLoadingView()
                    Tool().showErrorInfo(code, errMsg)
                }
            }
            //add Loading view
            if model.ignoreFlag == false{//submit时才显示submitting
                ModelViewUtil.shared.showLoadingView(NSLocalizedString("Submitting...", comment: ""))
            }
            vm.submitAPPComment(model)
        }
        ModelViewUtil.shared.showAlertView(view)
    }
    private func toInverterNumberVC(_ animate: Bool = true) {
        let vc = JobDetailInvertersListViewController()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: animate)
    }
    private func toImageListVC(_ index: Int){
        guard index < JobDetailModelHelper.shared.jobDetailModel.pvd_checklists.count else {
            return
        }
        //如果当前checklist是mid-installation check-up或者testing and commissioning checklist而且上一步没有完成
        let serverModel = JobDetailModelHelper.shared.jobDetailModel.pvd_checklists[index]
        let checklistID = serverModel.id
        if checklistID == ChecklistFixedId.midInstall.rawValue && !JobDetailModelHelper.shared.jobDetailModel.checkInSelfieDoneFlag {
            let alertMsg = "Please take '\(JobDetailModelHelper.shared.jobDetailModel.checkInSelfieTitle)'"
            Tool().showAlertViewWithOneBtn(title: "Temporary Locked",message: alertMsg, confirmStr: "Dismiss")
        }else if checklistID == ChecklistFixedId.testAndCommission.rawValue && !JobDetailModelHelper.shared.jobDetailModel.midInstallationSelfieDoneFlag{
            let alertMsg = "Please take '\(JobDetailModelHelper.shared.jobDetailModel.midInstallationSelfieTitle)'"
            Tool().showAlertViewWithOneBtn(title: "Temporary Locked",message: alertMsg, confirmStr: "Dismiss")
        }else{
            self.forwardToImageListVC(index)
        }
    }
    private func forwardToImageListVC(_ index: Int){
        let vc =  JobImageListViewController()
        JobDetailModelHelper.shared.checklistModel = JobDetailModelHelper.shared.jobDetailModel.pvd_checklists[index]
        JobDetailModelHelper.shared.checklistModel.pvdId = JobDetailModelHelper.shared.jobDetailModel.id
        self.navigationController?.pushViewController(vc,animated: false)
    }
    fileprivate func showEditCheckListText(_ serverModel: PVDChecklistModel){
        let vc = EditChecklistTextViewController()
        serverModel.pvdId = JobDetailModelHelper.shared.jobDetailModel.id
        vc.serverModel = serverModel
        vc.saveClosure = { (checkModel) in
            //0.必须先插入数据库，因为broadCast时，有地方（flush upload）会用到本地数据的统计
            DBManager.shared.insertChecklistData(model: checkModel)
            checkModel.oper_type = DataOperType.Add.rawValue
            //1.增加到当前list中，刷新数据
            if let index = JobDetailModelHelper.shared.jobDetailModel.pvd_checklists.firstIndex(where: {$0.id == checkModel.id}){
                JobDetailModelHelper.shared.jobDetailModel.pvd_checklists[index] = checkModel
                JobDetailModelHelper.shared.jobDetailModel.broadCastChecklistData()
            }
            //2.上传
            UploadManager.shared.uploadChecklistBoolOrText(checklistModel: checkModel)
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    private func toClickBoolItemOfChecklist(_ index: Int){
        let currentCheckListModel = JobDetailModelHelper.shared.jobDetailModel.pvd_checklists[index]
        currentCheckListModel.pvdId  = JobDetailModelHelper.shared.jobDetailModel.id
        //1.local data exist
        if currentCheckListModel.answer == "true" {
            currentCheckListModel.answered_at = ""
            currentCheckListModel.answer = ""
            currentCheckListModel.full_name = ""
        }else{
            currentCheckListModel.answered_at = DateUtil().getCurrentDatetime()
            currentCheckListModel.answer = "true"
            currentCheckListModel.full_name = APPConfig.loginInfo.fullName
        }
        //0.必须先插入数据库，因为broadCastChecklistData时，有地方会用到本地数据
        DBManager.shared.insertChecklistData(model: currentCheckListModel)
        currentCheckListModel.oper_type = DataOperType.Add.rawValue
        //1.增加到当前list中，刷新数据
        JobDetailModelHelper.shared.jobDetailModel.pvd_checklists[index] = currentCheckListModel
        JobDetailModelHelper.shared.jobDetailModel.broadCastChecklistData()
        //3.上传
        UploadManager.shared.uploadChecklistBoolOrText(checklistModel: currentCheckListModel)
    }
    //MARK: to DER register
    private func toDERRegister(){
        if JobDetailModelHelper.shared.jobDetailModel.isInstallerFlag {//当前用户是installer才能操作DER Register
            let vc = DERRegisterViewController()
            vc.gwtID = JobDetailModelHelper.shared.jobDetailModel.gwt_id
            self.navigationController?.pushViewController(vc, animated: false)
        }
        
    }
    //finish job的时候如果有本地数据，弹出框中增加upload的button
    private func alertViewWithUpload(_ title : String = "", message : String,cancelBtnStr: String = "Cancel", textAlignment: NSTextAlignment = .center, toContinueType: FlushUploadType){
        Tool().showAlertViewWithTwoBtns(title: title, message: message, cancelStr: cancelBtnStr, confirmStr: "Upload&Continue", yesClosure:  {
            self.flushUpload(toContinueType)
        })
    }
    //MARK: - 上传job的 本地数据，且显示uploading 信息
    private func flushUpload(_ toContinueType: FlushUploadType){
        if Connectivity.isConnectedToInternet  {
            if JobDetailModelHelper.shared.jobDetailModel.detailModifyFlag{
                let view = FlushUploadView()
                self.navigationController?.view.addSubview(view)
                view.snp.makeConstraints { make in
                    make.edges.equalToSuperview()
                }
                //停止Flush reupload
                view.stopFlushUploadClosure = {[weak self] in
                    guard let strongSelf = self else {return }
                    UploadManager.shared.cancelFlushUpload()
                    strongSelf.loadData(false)
                    view.removeFromSuperview()
                }
                ModelViewUtil.shared.showLoadingView("Locating...")
                UploadManager.shared.uploadLocalDataByPVDJob(JobDetailModelHelper.shared.jobDetailModel.id, uploadingClosure: { [weak self] (needUploadCnt,uploadSuccessCnt, uploadFaildCnt) in
                    ModelViewUtil.shared.hideLoadingView()
                    guard let strongSelf = self else {return}
                    view.uploadingLabel.text = "Uploading \(uploadSuccessCnt)/\(needUploadCnt)"
                    if needUploadCnt == uploadSuccessCnt + uploadFaildCnt {//上传完毕
                        strongSelf.loadData(false)
                        if let _ = view.superview {//可能stopFlushUpload时候被remove掉了，所以此处要判断下，保持数据统一
                            view.removeFromSuperview()
                        }
                        if uploadSuccessCnt == needUploadCnt  {//全部上传成功
                            if toContinueType == .flushUpload {//单纯的上传
                                //无代码处理
                            }else{//finish job , panel installed
                                strongSelf.loadDataAndToContinue(toContinueType)
                            }
                        }else{//部分数据，上传失败
                            Tool().showAlertViewWithTwoBtns(title: "Partial upload failed", message: "Some data failed to upload, please upload again.",cancelStr: "Cancel", confirmStr: "Re-upload",noClosure: nil, yesClosure: {
                                strongSelf.flushUpload(.flushUpload)
                            })
                        }
                    }
                })
            }
        }else{
            Tool().showFailureInfo()
        }
    }
    //MARK: 用户finish job，panel installed上传完本地数据后，拉取最新数据，继续走finish job或panel installed的流程
    private func loadDataAndToContinue(_ toContinueType: FlushUploadType) {
        let vm = JobDetailService()
        //set block
        vm.setBlockAfterNetwork({ (result , _) -> Void in
            ModelViewUtil.shared.hideLoadingView()
            //本地数据上传完毕后
            if  toContinueType == .finishJob {//continue finish job
                self.finishJob()
            }else if toContinueType == .panelInstalled{//continue panel installed
                //如果panel installed了，将缓存到本地的date of completion 清除掉
                if JobDetailModelHelper.shared.jobDetailModel.spv_check && JobDetailModelHelper.shared.jobDetailModel.spv_installed {
                    Tool().removeOfUserDefaults(key: self.panelInstalledDateOfCompletionKey)
                }
                self.checkSPVPanelInstalledAfterUploadLocalData()
            }
        }) { (code, error) -> Void in
            ModelViewUtil.shared.hideLoadingView()
            self.customView.showFaildView()
            Tool().showErrorInfo(code, error)
        }
        //add Loading view
        if toContinueType == .finishJob {//finish job
            ModelViewUtil.shared.showLoadingView(NSLocalizedString("pvd.detail.finishJob", comment: ""))
        }else if toContinueType == .panelInstalled {//panel installed
            ModelViewUtil.shared.showLoadingView("Checking...")
        }
        vm.getInstallationsDetail()
    }
    //MARK: Panel Installer第一步
    //MARK: 开始panel installed，拉取最新数据检查spv_check, spv_installed是否有变化
    private func getDetailBeforePanelInstalled(){
        //0.在panel install校验前，如果有网络就先拉下网络数据，否则无网直接panel installed
        if JobDetailModelHelper.shared.jobDetailModel.isInstallerFlag {
            if Connectivity.isConnectedToInternet {//有网路的处理步骤
                let vm = JobDetailService()
                let oldSPVCheck: Bool = JobDetailModelHelper.shared.jobDetailModel.spv_check
                //set block
                vm.setBlockAfterNetwork({ (result , _) -> Void in
                    ModelViewUtil.shared.hideLoadingView()
                    
                    //校验spv状态是否从abled变成disabled
                    let newSPVCheck = JobDetailModelHelper.shared.jobDetailModel.spv_check
                    if oldSPVCheck && !newSPVCheck {
                        Tool().showAlertViewWithOneBtn(message: R.string.localizable.theRetailerHasDisabledSPVVerificationForTheCurrentJob())
                    }else{
                        if JobDetailModelHelper.shared.jobDetailModel.spv_installed == false {//如果最新数据也没有spv installed了，就跳转到date of commissioning
                            self.toDateOfCommissioningVC()
                        }
                    }
                    
                }) { (code, error) -> Void in
                    ModelViewUtil.shared.hideLoadingView()
                    Tool().showErrorInfo(code,error)
                }
                //add Loading view
                ModelViewUtil.shared.showLoadingView("Checking...")
                vm.getInstallationsDetail()
                
            }else{
                self.toDateOfCommissioningVC()
            }
        }
    }
    //MARK: Panel Installer第二步
    //MARK: 显示panel installed选择date of commissioning 日期的界面
    private func toDateOfCommissioningVC(){
        //检查所有后台checklist是否通过校验,continueFlag： true表示只有电工单没有完成，所有只是提示不阻断操作
        let (checklistMsg, minImagesCntMsg, notDoneChecklistIDs) = InstallationDetailVCHelper.shared.checkIfChecklistAllDoneForPanelInstalled()
        if checklistMsg != "" || minImagesCntMsg != ""{
            var combineMsg = checklistMsg
            if minImagesCntMsg != "" {
                combineMsg += "\n* Additional checklist photos required for the following sections:\n" + minImagesCntMsg
            }
            Tool().showAlertViewWithOneBtn(title: "Job can not set commissioning  date due to following tasks",message: combineMsg,messageTextAlignment: NSTextAlignment.left) {
                if notDoneChecklistIDs.count == 1 && notDoneChecklistIDs[0] == ChecklistFixedId.certificateOfElectricalSafety.rawValue {//如果只有ESC没有做，则提示后继续panel的操作
                    self.forwardToPanelInstalled()
                }
            }
        }else{
            self.forwardToPanelInstalled()
        }
    }
    //MARK: - 跳转到PanelInstalled界面
    private func forwardToPanelInstalled(){
        let vc = PanelInstallAlertViewController()
        vc.continueClosure = { [weak self](dateStr) in
            guard let strongSelf = self else {return}
            strongSelf.panelInstalledDateOfCompletion = dateStr
            Tool().setValueOfUserDefaults(strongSelf.panelInstalledDateOfCompletion, key: strongSelf.panelInstalledDateOfCompletionKey)
            strongSelf.checkSPVPanelInstalled()
        }
        if let date = UserDefaults.standard.object(forKey: self.panelInstalledDateOfCompletionKey) as? String {
            vc.cacheDateOfCompletion = date
        }
        self.navigationController?.pushViewController(vc, animated: false)
    }
    //MARK: Panel Installer第三步
    //MARK: 检查需要panel install的必填项
    private func checkSPVPanelInstalled(){
        //1.检查是否有invalid 的panel number
        for panelModel in JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers {
            if panelModel.spv_status.lowercased() == "invalid" {
                Tool().showAlertViewWithOneBtn(message: "Invalid panel serial number. Please confirm and try again.")
                return
            }
        }
        //2.panel number数量是否匹配
        let scannedPanelNumberCnt: String = "\(JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers.count)"
        let planPanelNumberCnt = "\(JobDetailModelHelper.shared.jobDetailModel.system_detail.panel_plant_count)"
        if planPanelNumberCnt != scannedPanelNumberCnt {
            Tool().showAlertViewWithOneBtn(message: "The actual number of panels installed do not match with the original quantity.\n\nPanel quantity : " + planPanelNumberCnt + "\nPanel serial numbers: " + scannedPanelNumberCnt)
            return
        }
        //3.1 服务器上的panel number或本地的图片是否为空
        for panelModel in JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers {
            if panelModel.image == "" {
                Tool().showAlertViewWithOneBtn(message: "Please upload a valid photo of the panel's serial number.")
                return
            }
        }
        //6. panel numbers，Installation address and date of completion，是否有本地数据或者
        //                if self.model.panelNumbersModifyFlag || self.model.detailModifyFlag {
        if JobDetailModelHelper.shared.jobDetailModel.detailModifyFlag{
            self.alertViewWithUpload(message: NSLocalizedString("pvd.detail.checklist.panelinstalled.localpanelnumbers.check.tip", comment: ""),toContinueType: .panelInstalled)// continue panel installed
            return
        }
        //7,8
        self.checkSPVPanelInstalledAfterUploadLocalData()
        
    }
    //MARK: Panel Installer第四步
    //MARK: 检查数据panel是否都verified，安装地址是否不为空
    private func checkSPVPanelInstalledAfterUploadLocalData(){
        //7.是否验证了所有的panel numer
        if let _ = JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers.firstIndex(where: {$0.spv_status.lowercased() == "verifying" || $0.spv_status.lowercased() == "unverified"}){
            Tool().showAlertViewWithOneBtn(message: "The previous panel is still being verified. Please try again later.")
            return
        }
        //8.Job是否有地址
        if JobDetailModelHelper.shared.jobDetailModel.install_address.installation_address == "" {
            Tool().showAlertViewWithOneBtn(message: "The current job is missing address information, please contact the retailer to fill out and try again.")
            return
        }
        //
        self.checkSPVPanelInstalledCommonOther()
    }
    //MARK: Panel Installer第五步
    //MARK: 检查数据安装地址的经纬度，是否在安装范围内
    private func checkSPVPanelInstalledCommonOther(){
        //9.Installation address的经纬度是否为空
        let installAddress = JobDetailModelHelper.shared.jobDetailModel.install_address
        let installationLocation = installAddress.location
        if installationLocation.longitude == "" || installationLocation.latitude == "" {
            Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.panalNumbers.spv.gps.notlocated", comment: ""))
            return
        }
        //10.是否存储了上次Panel Installed的离线经纬度
        //上次存储了定位位置
        if let latitudeValue = UserDefaults.standard.object(forKey: self.panelInstalledLatitudeKey) as? String, let longitudeValue = UserDefaults.standard.object(forKey: self.panelInstalledLongitudeKey) as? String {
            self.devationLocation.latitude = latitudeValue
            self.devationLocation.longitude = longitudeValue
            self.panelInstallValidateAPI()
        }else{//上次没有存储定位位置
            //11：location 定位是否开启
            let status  = CLLocationManager.authorizationStatus()
            if JobDetailModelHelper.shared.jobDetailModel.spv_check {
                if status == .denied || status == .restricted {
                    Tool().showAlertViewWithTwoBtns(title: R.string.localizable.locationServicesHaveToBeEnabledWhenUsingTheApp(),message: R.string.localizable.turnOnLocationServicesToVerifyRequiredOnsiteDataEgPanelsSerialNumbers(), cancelStr: R.string.localizable.cancel(), confirmStr: R.string.localizable.settings(), yesClosure:  {
                        if  UIApplication.shared.canOpenURL(URL(string: UIApplication.openSettingsURLString)!) {
                            UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
                        }
                    })
                    return
                }
            }
            //12.能否定位GPS/网络
            self.devationLocation.latitude = ""
            self.devationLocation.longitude = ""
            //
            self.panelInstalledLcation.latitude = ""
            self.panelInstalledLcation.longitude = ""
            
            LocationManager.shared.subscription(.single).fetchWithCompletion {[weak self](location, error) in
                guard let strongSelf = self else {
                    return
                }
                //获取安装位置的经纬度
                let installedAddress = JobDetailModelHelper.shared.jobDetailModel.install_address
                let installedLocation = installedAddress.location
                let devationSetting = JobDetailModelHelper.shared.jobDetailModel.installation_position_deviation
                if location != nil {
                    var currentLocation: CLLocation = location!
                    if Tool().isLocationOutOfChina(location!.coordinate) == false{
                        let gcj02Coordinate = YJLocationConverter.yj_WGS84Convert(toGCJ02: location!.coordinate)
                        currentLocation = CLLocation(latitude: gcj02Coordinate.latitude, longitude: gcj02Coordinate.longitude)
                    }
                    let latitude = installedLocation.latitude
                    let longitude = installedLocation.longitude
                    if latitude != "" && longitude != "", let doubleLatitude = Double(latitude), let doubleLongitude = Double(longitude) {
                        let installedLocation = CLLocation(latitude: doubleLatitude, longitude: doubleLongitude)
                        
                        //单位是m
                        let distanceFromCurrentLocation = currentLocation.distance(from: installedLocation)
                        
                        //13.当前位置是否在owner 安装地址范围内：不在范围内
                        if distanceFromCurrentLocation > devationSetting{
                            
                            //14.扫描位置是否在安装范围内
                            for panelModel in JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers {
                                if let latitide = panelModel.latitude, let longitude = panelModel.longitude {
                                    let panelInstalledLocation = CLLocation(latitude: latitide, longitude: longitude)
                                    
                                    let distance = installedLocation.distance(from: panelInstalledLocation)
                                    //获取系统设置的最小距离的值（单位：米）
                                    if distance <= devationSetting{
                                        
                                        strongSelf.devationLocation.latitude = "\(panelInstalledLocation.coordinate.latitude)"
                                        strongSelf.devationLocation.longitude = "\(panelInstalledLocation.coordinate.longitude)"
                                        break
                                    }
                                }
                            }
                            if strongSelf.devationLocation.latitude == "" && strongSelf.devationLocation.longitude == "" {
                                Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.checklist.panelinstalled.installaddress.check.tip", comment: ""))
                            }else{//在panel number中存在范围内的经纬度，提示用s户是否使用panel number中的位置
                                Tool().showAlertViewWithTwoBtns(message: NSLocalizedString("pvd.detail.checklist.panelinstalled.usescanningaddress.tip.two", comment: ""), cancelStr: "No",confirmStr: "OK", yesClosure:  {
                                    strongSelf.panelInstallValidateAPI()
                                })
                                return
                            }
                        }else{//当前位置是否在owner 安装地址范围内：在范围内
                            strongSelf.panelInstalledLcation.latitude = "\(currentLocation.coordinate.latitude)"
                            strongSelf.panelInstalledLcation.longitude = "\(currentLocation.coordinate.longitude)"
                            
                            strongSelf.devationLocation.latitude = "\(currentLocation.coordinate.latitude)"
                            strongSelf.devationLocation.longitude = "\(currentLocation.coordinate.longitude)"
                            strongSelf.panelInstallValidateAPI()
                        }
                    }else{
                        Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.checklist.panelinstalled.installaddress.required.tip", comment: ""))
                        return
                    }
                }else{//定位失败
                    let latitude = installedLocation.latitude
                    let longitude = installedLocation.longitude
                    if latitude != "" && longitude != "", let doubleLatitude = Double(latitude), let doubleLongitude = Double(longitude) {
                        let installedLocation = CLLocation(latitude: doubleLatitude, longitude: doubleLongitude)
                        //14.扫描位置是否在安装范围内
                        for panelModel in JobDetailModelHelper.shared.jobDetailModel.pvd_serial_numbers {
                            if let latitide = panelModel.latitude, let longitude = panelModel.longitude {
                                let panelInstalledLocation = CLLocation(latitude: latitide, longitude: longitude)
                                
                                let distance = installedLocation.distance(from: panelInstalledLocation)
                                //获取系统设置的最小距离的值（单位：米）
                                if distance <= devationSetting{
                                    strongSelf.devationLocation.latitude = "\(panelInstalledLocation.coordinate.latitude)"
                                    strongSelf.devationLocation.longitude = "\(panelInstalledLocation.coordinate.longitude)"
                                    break
                                }
                            }
                        }
                        if strongSelf.devationLocation.latitude == "" && strongSelf.devationLocation.longitude == "" {
                            Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.checklist.panelinstalled.availableaddress.check.tip", comment: ""))
                        }else{//在panel number中存在范围内的经纬度，提示用户是否使用panel number中的位置
                            Tool().showAlertViewWithTwoBtns(message: NSLocalizedString("pvd.detail.checklist.panelinstalled.usescanningaddress.tip", comment: ""), cancelStr: "No",confirmStr: "OK", yesClosure:  {
                                strongSelf.panelInstallValidateAPI()
                            })
                            return
                        }
                    }
                    
                }
            }
        }
    }
    //MARK: Panel Installer第五步
    //MARK: 提交panel installed api，提交成功刷新数据
    private func panelInstallValidateAPI()
    {
        //15.有网络直接调用panel installe的 api
        if Connectivity.isConnectedToInternet {
            let vm = JobDetailService()
            //set block
            vm.setBlockAfterNetwork({ (result , _) -> Void in
                ModelViewUtil.shared.hideLoadingView()
                //缓存数据，并设置panel instealled为true,且检查是否需要重签数据
                self.loadData(false,checkIfNeedResignFlag: true)
                //请求成功后，删除保存的经纬度
                Tool().removeOfUserDefaults(key: self.panelInstalledLatitudeKey)
                Tool().removeOfUserDefaults(key: self.panelInstalledLongitudeKey)
                Tool().removeOfUserDefaults(key: self.panelInstalledDateOfCompletionKey)
            }) { (code, error) -> Void in
                ModelViewUtil.shared.hideLoadingView()
                if error == RequestErrorType.NetworkError.rawValue{
                    let latitude = self.panelInstalledLcation.latitude
                    let longitude = self.panelInstalledLcation.longitude
                    if latitude != "" && longitude != "" {
                        UserDefaults.standard.set(latitude, forKey: self.panelInstalledLatitudeKey)
                        UserDefaults.standard.set(longitude, forKey: self.panelInstalledLongitudeKey)
                        
                        Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.checklist.panelinstalled.getcurrentlocation.withoutnetwork", comment: ""))
                    }else{//使用的是扫描panel number时地址
                        Tool().showAlertViewWithOneBtn(message: "We can't verify your data due to network failure. Please try again later.")
                        
                    }
                }else{
                    var alertMsg = error
                    if error.contains(",Serial Number not valid") {//特别处理serial number已经被其他job安装的提示（例如：Serial Number not valid(Serial Number is valid for the model, but already installed for serial ET-AMBERTEST00000107),Serial Number not valid(Serial Number is valid for the model, but already installed for serial ET-AMBERTEST00000109)）
                        alertMsg = error.replacingOccurrences(of: ",Serial Number not valid", with: ".\nSerial Number") + "."//特别处理
                    }
                    Tool().showErrorInfo(code, alertMsg)
                }
            }
            //add Loading view
            ModelViewUtil.shared.showLoadingView("Checking...")
            vm.panelInstalledValidate(self.devationLocation,dateOfCompletion: self.panelInstalledDateOfCompletion)
        }else{
            //没有网络，保存panel installed的经纬度
            let latitude = self.panelInstalledLcation.latitude
            let longitude = self.panelInstalledLcation.longitude
            if latitude != "" && longitude != "" {
                UserDefaults.standard.set(latitude, forKey: self.panelInstalledLatitudeKey)
                UserDefaults.standard.set(longitude, forKey: self.panelInstalledLongitudeKey)
                Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.checklist.panelinstalled.getcurrentlocation.withoutnetwork", comment: ""))
            }else{//使用的是扫描panel number时地址
                Tool().showAlertViewWithOneBtn(message: "We can't verify your data due to network failure. Please try again later.")
                
            }
        }
    }
    override var preferredStatusBarStyle: UIStatusBarStyle {
        if #available(iOS 13.0, *) {
            return .darkContent
        } else {
            return .default
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
}
